
<template>
  <view class="uni-container">
    <uni-forms ref="form" v-model="formData" :rules="rules" validateTrigger="bind">
      <uni-forms-item name="username" label="学生工号/姓名">
				<el-select style="width: 100%;" v-model="formData.username"
								filterable remote placeholder="请输入学生工号或姓名"
								:remote-method="searchStudent" :loading="studentLoading">
					 <el-option
						 v-for="item in formOptions.studentOptions"
						 :key="item.value"
						 :label="item.label"
						 :value="item.value">
					 </el-option>
				 </el-select>
			</uni-forms-item>
			<uni-forms-item name="tclass_id"  
				v-for="(key,index) in formData.tclass_id" 
				:label="'教学班'+(index+1)"
				:key="key.key"
				:prop="'tclass_id.' + index + '.value'"
			>
			<view style="display: flex;flex-direction: row;">
				<el-cascader :props="lazyProps"  v-model="key.value" style="width: 300px;"></el-cascader>
				<button class="uni-button" style="width: 80px; margin-left: 10px;" type="warn" @click="delClass(key)">删除</button>
			</view>
			</uni-forms-item>
			<view class="uni-button-group" style="margin-bottom: 40rpx;">
				<button class="uni-button"  style="width: 100px;" @click="addClass">新增</button>
			</view>
			<uni-forms-item name="credit" label="总学分">
				<uni-easyinput placeholder="总学分" type="number" v-model="formData.credit" />
			</uni-forms-item>

      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator url="/pages/student/schedule/list" style="margin-left: 15px;">
            <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import validator from '@/js_sdk/validator/user-schedule.js';
	import Vue from 'vue'

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'hr-userSchedule';

  function getValidator(fields) {
    let reuslt = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        reuslt[key] = validator[key]
      }
    }
    return reuslt
  }

  export default {
    data() {
      return {
				studentLoading: false,
				lazyProps:{
					lazy : true,
					// multiple: true,
					lazyLoad : (node , resolve) => {
						if(node.level == 3) return resolve([])
						const {level , data} = node , params = [{},{college: data && data.value},{ course : data && data.value }][level], load = [this.loadCollege,this.loadCourse,this.loadClass][level]
						// async load
						load(params).then(r=>{
							resolve(r.map(({id , name}) => {
								return {value : id , label : name , leaf : level >= 2}
							}))
						}).catch(()=>{
							resolve()
						})
					}
				},
        formData: {
					"username": "",
					"tclass_id": [{value: '',key: Date.now()}],
					"credit": 38,
					"usedcredit":0,
					"schedule": []
				},
				formOptions: {
					studentOptions:[],
				  "term_localdata": [
				    {
				      "text": "上学期",
				      "value": 0
				    },
				    {
				      "text": "下学期",
				      "value": 1
				    }
				  ]
				},
        rules: {
          ...getValidator(["username","credit","schedule"])
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
			/**
			 * 删除教学班列
			 */
			delClass(item){
				var index = this.formData.tclass_id.indexOf(item)
				if (index !== -1) {
					this.formData.tclass_id.splice(index, 1)
				}
			},
			
			/**
			 * 添加教学班列
			 */
			addClass(){
				this.formData.tclass_id.push({
					value: '',
					key: Date.now()
				});
			},
			
			/**
			 * 异步加载学院信息
			 * @param {Object} value
			 */
			loadCollege(params){
				return new Promise(function(resolve , reject){
					db.collection('hr-college')
						.where(params)
						.get().then((res)=>{
							let {affectedDocs , data} = res.result
							if(affectedDocs == 0){
								reject()
							}else{
								let result = data.map(({college_id:id,name:name})=>{
									return {id,name}
								})
								resolve(result);
							}
					})
				})
			},
			
			/**
			 * 异步加载课程信息
			 * @param {Object} value
			 */
			loadCourse(params){
				return new Promise(function(resolve , reject){
						db.collection('hr-course')
						.where(params)
						.get().then((res)=>{
							let {affectedDocs , data} = res.result
							if(affectedDocs == 0){
								reject()
							}else{
								let result = data.map((detail)=>{
									let {course_id:id,course_name,credit} = detail
									let name = `${course_name} - ${credit}学分`
									return {id,name,credit}
								})
								resolve(result);
							}
						})
				})
			},
			
			/**
			 * 异步加载班级信息
			 * @param {Object} value
			 */
			loadClass(params){
				const character = ['周一', '周二', '周三', '周四', '周五'];
				const time = ['09:00-10:20', '10:40-12:00', '12:30-13:50', '14:00-15:20', '15:30-16:50', '17:00-18:20','19:00-20:20','20:30-21:50'];
				Object.assign(params,{ optionalNumber:dbCmd.gt(0) })
				return new Promise(function(resolve , reject){
					db.collection('teaching-class')
					.where(params)
					.get().then((res)=>{
						let {affectedDocs , data} = res.result
						if(affectedDocs == 0){
							reject()
						}else{
							let result = data.map((detail)=>{
								let {class_id , day , node} = detail
								let id = class_id , name =  `${class_id}  ${character[day]}-${time[node]}`
								return {id,name}
							})
							resolve(result);
						}
					})
				}) 
			},
			
			// 搜索学生
			async searchStudent(query) {
				if (query !== '') {
					this.studentLoading = true;
					await this.$request('schedule/searchStudent')
					.then((res)=>{
						this.studentLoading = false;
						this.formOptions.studentOptions = res.filter(item => {
							return item.label.toLowerCase()
								.indexOf(query.toLowerCase()) > -1;
						});
					})
				} else {
					this.formOptions.studentOptions = [];
				}
			},
			
			/**
			 * 触发表单提交
			 */
			submit() {
			  uni.showLoading({
					title: '提交中',
			    mask: true
			  })
			  this.$refs.form.submit().then((res) => {
			    this.submitForm(res)
			  }).catch((errors) => {
			    uni.hideLoading()
			  }).finally(() => {
						uni.hideLoading()
				})
			},

     async submitForm(value) {
			 let year = new Date().getFullYear() // 当前年份
			 let term = new Date().getMonth()+1 < 6 ? 0 : 1 // 划分为上半年和下半年
				let {tclass_id,username,credit} = this.formData
				value.tclass_id = tclass_id
				// 每个课程获取详细 -> 扣除课程人数 -> 扣除学分 -> 插入课程表 

				let course = this.formData.tclass_id
				if(!this.empty(course[0])){
					await this.$request('course/selectionCourse',{username,course,credit}).then((res)=>{
						let {usedCredits , result} = res.data
						value.usedcredit = usedCredits
						value.schedule  = result
					})
				}else{
					value.usedcredit = 0
					value.schedule  = []
				}
				value.year = year
				value.term = term
				console.log(value)
        // 使用 uni-clientDB 提交数据
        db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateTo({
						url: '/pages/student/schedule/list'
					}), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>

